package com.mrtaohuan.servlet.listener;

import java.io.File;
import java.util.Map;

import javax.servlet.ServletContextEvent;

import lombok.extern.java.Log;

import com.google.appengine.labs.repackaged.com.google.common.collect.Maps;
import com.google.inject.AbstractModule;
import com.google.inject.Guice;
import com.google.inject.Injector;
import com.google.inject.Singleton;
import com.google.inject.servlet.GuiceServletContextListener;
import com.google.inject.servlet.ServletModule;
import com.googlecode.objectify.ObjectifyFilter;
import com.mrtaohuan.data.OfyFactory;
import com.mrtaohuan.render.HttpContext;
import com.mrtaohuan.servlet.OrcaServlet;
import com.mrtaohuan.servlet.filter.AuthenticationFilter;
import com.mrtaohuan.servlet.filter.HttpRequestFilter;
import com.sun.jersey.api.core.PackagesResourceConfig;
import com.sun.jersey.guice.spi.container.servlet.GuiceContainer;

@Log
public class GuiceConfigListener extends GuiceServletContextListener {

	static class ExtendServletModule extends ServletModule {
		@Override
		protected void configureServlets() {
			Map<String, String> appstatsParams = Maps.newHashMap();
			appstatsParams.put("logMessage",
					"Appstats: /admin/appstats/details?time={ID}");
			appstatsParams.put("calculateRpcCosts", "true");

			filter("/*").through(HttpRequestFilter.class);

			// filter("/*").through(AppstatsFilter.class, appstatsParams);
			// serve("/appstats/*").with(AppstatsServlet.class);

			filter("/*").through(ObjectifyFilter.class);
			filter("/admin", "/admin/*").through(AuthenticationFilter.class);

			serve("/orca.txt").with(OrcaServlet.class);

			Map<String, String> params = Maps.newHashMap();
			params.put(PackagesResourceConfig.PROPERTY_PACKAGES,
					"com.mrtaohuan.action");
			serve("/*").with(GuiceContainer.class, params);
			
		}
	}

	public static class ExtendModule extends AbstractModule {
		@Override
		protected void configure() {
			requestStaticInjection(OfyFactory.class);

			// bind(AppstatsFilter.class).in(Singleton.class);
			// bind(AppstatsServlet.class).in(Singleton.class);
			bind(ObjectifyFilter.class).in(Singleton.class);
			bind(HttpContext.class);

		}

	}

	@Override
	public void contextInitialized(ServletContextEvent servletContextEvent) {
		long time = System.currentTimeMillis();

		super.contextInitialized(servletContextEvent);

		long millis = System.currentTimeMillis() - time;
		log.info("Guice initialization took " + millis + " millis");

		webRoot = servletContextEvent.getServletContext().getRealPath("")
				+ File.separator;

	}

	@Override
	protected Injector getInjector() {
		return Guice.createInjector(new ExtendServletModule(),
				new ExtendModule());
	}

	private static String webRoot;

	public static String getWebRoot() {
		return webRoot;
	}

}
